package com.jsoft.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.jsoft.core.RedisTemplate;
import com.jsoft.entity.LoginUser;
import com.jsoft.exception.BusinessException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Set;

import static com.jsoft.controller.Code.GET_ERR;

/**
 * 获取当前的登录用户对象
 *
 * @author : handsome Boy
 * @description :
 * @createDate : 2025/3/19 13:40
 */
public class AuthUtil {
    public AuthUtil() {
    }

    public static LoginUser getLoginUser(RedisTemplate redisTemplate) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String token = request.getHeader("Authorization");
        if (Objects.isNull(token)) {
            throw new BusinessException("用户未登录", GET_ERR);
        } else {

            Set<String> keys = redisTemplate.keys("token:*" + token);
            if (Objects.isNull(keys)) {
                throw new BusinessException("用户未登录", GET_ERR);
            } else {
                String tokenKey = (String) keys.toArray()[0];
                return (LoginUser) redisTemplate.getObject(tokenKey, new TypeReference<LoginUser>() {
                });

            }
        }

    }

}
